import java.io.*;
import java.util.*;
public class Demo17{
    static int N = 110,hh,tt,n,m;
    static int g[][] = new int[N][N];
    static int d[][] = new int[N][N];
    static int[] PII = new int[N];
    static PII[] q = new PII[N * N];
    public static int dfs(){
        hh = 0; tt = -1;
        d[0][0] = 0;
        q[++tt] = new PII(0,0);

        int[] dx = {-1,0,1,0};
        int[] dy = {0,1,0,-1};
        while(hh <= tt){
            PII t = q[hh++];
            for(int i = 0; i < 4; i++){
                int x = t.first + dx[i];
                int y = t.second + dy[i];
                if(x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1){
                    d[x][y] = d[t.first][t.second] + 1;
                    q[++tt] = new PII(x,y);
                }
            }
        }
        return d[n - 1][m - 1];
    }
    public static void main(String[] args)throws IOException {
        BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(System.out));
        String[] s = re.readLine().split(" ");
        n = Integer.parseInt(s[0]);
        m = Integer.parseInt(s[1]);

        for(int i = 0; i < n; i++){
            String[] st = re.readLine().split(" ");
            for(int j = 0; j < m; j++){
                g[i][j] = Integer.parseInt(st[j]);
                d[i][j] = -1;
            }
        }
        System.out.println(dfs());
        re.close();
        wr.close();
    }
}
class PII{
    int first,second;
    public PII(int first,int second){
        this.first  = first;
        this.second = second;
    }
}